package jianyongjie.loginzuul;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
* @Description: 自定义拦截器
* @Author: JianYongJie
* @Version: 1.0
* @Date:  2022/5/31 17:05
*/
@Component
public class LoginZuul extends  ZuulFilter {

    @Override
    public String filterType() {

        // “pre”前置（”custom”自定义一般是前置），“routing”路由，“post”后置，以及“error”异常Filter
        return "pre";
    }

    @Override
    public int filterOrder() {
        // 设置执行顺序，数字越小会先执行
        return -1;
    }

    @Override
    public boolean shouldFilter() {
        // 获取请求
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 进行判断
        String requestURI = request.getRequestURI();
        // 如果是注册页面，登陆页面和静态资源就不拦截
        if (requestURI.endsWith("login")||requestURI.endsWith("register")||requestURI.endsWith("/static/")){
            return false;
        }

        // 反之就放行
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 获取响应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        // 获得token
        String token = request.getHeader("token");
        // 判断是否有token
        if (token==null){
            // 如果等于null，就给前端返回错误信息
            Map<String, Object> map = new HashMap<>();
            // 设置值
            map.put("success",false);
            map.put("msg","登录失效请重新登录");
            // 设置编码集
            response.setContentType("application/json;charset=utf-8");
            // 将对象转为json格式
            String s = JSON.toJSONString(map);
            // 清除状态401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                // 将数据发送浏览器
                response.getWriter().print(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 阻止继续执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);

        }
        return null;
    }
}
